<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"
    />
    <title>canvas limit</title>
  </head>
  <body>
    <div>
      <span>内存单位: MB</span>
      <input type="number" id="number" />
    </div>
    <div>
      <button id="create">创建</button>
    </div>
    <script>
      // canvas放进该全局变量，防止GC
      let canvasQueue = [];

      // 创建 1MB canvas
      const create1MCanvas = () => {
        const size = 512;
        const canvas = document.createElement("canvas");
        canvas.width = size;
        canvas.height = size;
        const context = canvas.getContext("2d");
        context.fillRect(0, 0, size, size);
        return canvas;
      };

      // 创建 n x 1MB canvas
      const createNMCanvas = (n) => {
        for (let i = 0; i < n; i++) {
          canvasQueue.push(create1MCanvas());
        }
      };

      const input = document.querySelector("#number");
      const button = document.querySelector("#create");

      button.addEventListener("click", (event) => {
        event.preventDefault();
        const number = input.value;
        if (!Number.isNaN(Number(number))) {
          canvasQueue = [];
          createNMCanvas(Number(number));
          console.log(`创建${number}MB canvas成功`);
        }
      });
    </script>
  </body>
</html>